package com.corundumstudio.socketio.demo;

import com.corundumstudio.socketio.listener.*;
import com.corundumstudio.socketio.*;
import com.sun.javafx.collections.MappingChange;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class NamespaceChatLauncher {

    public static void main(String[] args) throws InterruptedException {
        final  Map<String,UUID> clientSessionMap=new HashMap<String, UUID>();
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9092);

        final SocketIOServer server = new SocketIOServer(config);
        final SocketIONamespace chat1namespace = server.addNamespace("/chat1");
        chat1namespace.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient socketIOClient) {
                String clientId=socketIOClient.getHandshakeData().getUrlParams().get("chat1Id").toString();
                clientId=clientId.replace("[","").replace("]","");
                clientSessionMap.put(clientId,socketIOClient.getSessionId());
                System.out.println(clientId);
            }
        });
        chat1namespace.addEventListener("message", ChatObject.class, new DataListener<ChatObject>() {
            @Override
            public void onData(SocketIOClient client, ChatObject data, AckRequest ackRequest) {
                // broadcast messages to all clients
                //chat1namespace.getBroadcastOperations().sendEvent("message", data);
                chat1namespace.getClient(clientSessionMap.get("chat1")).sendEvent("message",data);
            }
        });

        final SocketIONamespace chat2namespace = server.addNamespace("/chat2");
        chat2namespace.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient socketIOClient) {
                String clientId=socketIOClient.getHandshakeData().getUrlParams().get("chat2Id").toString();
                clientId=clientId.replace("[","").replace("]","");
                clientSessionMap.put(clientId,socketIOClient.getSessionId());
                System.out.println(clientId);
            }
        });
        chat2namespace.addEventListener("message", ChatObject.class, new DataListener<ChatObject>() {
            @Override
            public void onData(SocketIOClient client, ChatObject data, AckRequest ackRequest) {
                // broadcast messages to all clients
               // chat2namespace.getBroadcastOperations().sendEvent("message", data);
                chat2namespace.getClient(clientSessionMap.get("chat2")).sendEvent("message",data);
            }
        });

        server.start();

        Thread.sleep(Integer.MAX_VALUE);

        server.stop();
    }

}
